package com.neusoft.bizcore.activiti.converter;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.activiti.dto.ProcessDTO;
import com.neusoft.bizcore.activiti.model.Process;
import com.neusoft.bizcore.activiti.model.ProcessRole;
import com.neusoft.bizcore.activiti.repository.ProcessFormRepository;
import com.neusoft.bizcore.activiti.repository.ProcessRepository;
import com.neusoft.bizcore.activiti.repository.ProcessRoleRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class ProcessConverter extends AbstractConverter<Process, ProcessDTO> {

    @Autowired
    private ProcessRepository businessProcessRepository;
    @Autowired
    private ProcessFormRepository processFormRepository;
    @Autowired
    private ProcessRoleRepository processRoleRepository;

    @Override
    public Process toModel(final ProcessDTO dto) {

        Process model;

        if (dto.isNew()) {
            model = new Process();
        } else {
            model = this.businessProcessRepository.getOne(dto.getId());
        }

        model.setName(dto.getName());
        model.setCode(dto.getCode());

        model.getFormList().clear();
        dto.getFormIds().stream().map(k -> this.processFormRepository.getOne(k))
                .forEach(model.getFormList()::add);

        // 移除掉角色
        final List<ProcessRole> roles = model.getRoles().stream().collect(Collectors.toList());
        roles.stream().forEach(k -> {
            this.processRoleRepository.delete(k);
            model.getRoles().remove(k);
        });

        // 创建所有的关联角色
        dto.getRoles().stream().map(k -> {
            final ProcessRole entity = new ProcessRole();
            entity.setProcess(model);
            entity.setCode(k);
            return entity;
        }).forEach(model.getRoles()::add);

        return model;
    }

    @Override
    public ProcessDTO toDTO(final Process model, final boolean forListView) {

        final ProcessDTO dto = new ProcessDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        model.getFormList().stream().map(k -> k.getId())
                .forEach(dto.getFormIds()::add);

        model.getRoles().stream().map(k -> k.getCode()).forEach(dto.getRoles()::add);

        return dto;
    }

}
